package com.zc.webnews.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.zc.webnews.R;
import com.zc.webnews.application.Constant;
import com.zc.webnews.application.MyApplication;
import com.zc.webnews.utils.MyBmobUtils;
import com.zc.webnews.utils.SharepreferencesUtilSystemSettings;
import com.zc.webnews.view.WhorlView;

import java.util.HashMap;

import cn.bmob.v3.datatype.BmobFile;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;


/**
 * 登录界面
 * Created by Administrator on 2016/9/21 0021.
 */
public class LoginActivity extends BaseTranslucentActivity implements View.OnClickListener {
    private BmobFile bmobFile;
    //固定的ToolBar
    private Toolbar rootToolBar;
    private ImageView ivBack;
    private TextView title;
    //注册按钮
    private TextView tvToRegister;
    private String iconUrl;
    //账号
    private EditText userAccount;
    private String qqAccount;
    //密码
    private EditText userPassWord;
    private String qqPassword;
    //登录按钮
    private Button btn_login;
    private MyBmobUtils myBmobUtils;
    private boolean isLogin;
    private MyApplication myApplication;
    private SharedPreferences mSharedPreferences;
    private Dialog dialog;
    private int screen_height;
    private int screen_width;
    //QQ登陆 微信登陆 微博登陆
    private ImageView qq_login,wx_login,wb_login;
    public Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            //Log.e("handleMessage",msg.what+"");
            if (msg.what == 0){
                if (MyBmobUtils.identifySuccess){
                    //Log.e("identifySuccess",MyBmobUtils.identifySuccess+"");
                    dialog.dismiss();
                    MyApplication.mAccount.setAccount(userAccount.getText().toString());
                    MyApplication.mAccount.setPassword(userPassWord.getText().toString());
                    Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                    startActivity(intent);
                    MyApplication.mUser.setLogin(false);
                    SharepreferencesUtilSystemSettings.putValue(LoginActivity.this,
                            Constant.USERACCOUNTCOOKIE,MyApplication.mAccount.getAccount());
                    SharepreferencesUtilSystemSettings.putValue(LoginActivity.this,
                            Constant.USERPASSWORDCOOKIE,MyApplication.mAccount.getPassword());
                    SharepreferencesUtilSystemSettings.putValue(LoginActivity.this,
                            Constant.ISLOGIN, MyApplication.mUser.getIsLogin());
                    finish();
                }else {
                    dialog.dismiss();
                    Toast.makeText(LoginActivity.this,"用户名或者密码错误",Toast.LENGTH_LONG).show();
                    userPassWord.setText("");
                }
            }else if (msg.what==1){
                dialog.show();
                myBmobUtils.context = LoginActivity.this;
                myBmobUtils.addUser(MyApplication.mAccount.getAccount(),MyApplication.mAccount.getPassword());
            }else if (msg.what==2){
                dialog.dismiss();
                Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_LONG).show();
                Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                startActivity(intent);
            }

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkIsFirstLogin();
        getScreenWH();
        setContentView(R.layout.activity_login);
        initView();
        initTitle();
        initData();
        initListener();
        initDialog();
    }

    /**
     * 获取手机屏幕宽高
     */
    private void getScreenWH(){
        DisplayMetrics metrics = new DisplayMetrics();
        getWindow().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        screen_height = metrics.heightPixels;
        screen_width = metrics.widthPixels;
        Log.e("screen_height",screen_height+"");
        Log.e("screen_width",screen_width+"");
    }

    private void initDialog() {
        dialog = new Dialog(this);
        View view = getLayoutInflater().inflate(R.layout.dialog_view,null);
        WhorlView whorlView = (WhorlView) view.findViewById(R.id.loading);
        whorlView.start();
        Window window = dialog.getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        window.getDecorView().setPadding(50, 50, 50, 50);
        window.setBackgroundDrawableResource(android.R.color.transparent);
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = screen_width/2;
        layoutParams.height = screen_height/4;
        dialog.setCanceledOnTouchOutside(false);
        dialog.setContentView(view,layoutParams);
    }

    private void checkIsFirstLogin() {
        myApplication = (MyApplication) getApplication();
        Log.e("checkLoginisLogin", myApplication.isLogin + "");
        if (!myApplication.isLogin) {
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }
//        String account = MyApplication.mAccount.getAccount();
//        String password = MyApplication.mAccount.getPassword();
//        myBmobUtils.context = this;
//        myBmobUtils.queryAccount(account,password);
    }

    private void initData() {
        title.setText(R.string.Login);
        //隐藏顶部栏不需要的控件
        ivBack.setVisibility(View.GONE);
        myBmobUtils = new MyBmobUtils();

    }

    private void initListener() {
        tvToRegister.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        qq_login.setOnClickListener(this);
        wx_login.setOnClickListener(this);
        wb_login.setOnClickListener(this);
    }

    private void initTitle() {
        rootToolBar = (Toolbar) findViewById(R.id.login_title);
        ivBack = (ImageView) rootToolBar.findViewById(R.id.iv_back_titlebar);
        title = (TextView) rootToolBar.findViewById(R.id.tv_title_bar);
        setOrChangeTranslucentColor(rootToolBar, null, getResources().getColor(R.color.dip_red));
    }

    private void initView() {
        tvToRegister = (TextView) findViewById(R.id.tv_register);
        btn_login = (Button) findViewById(R.id.btn_login);
        userAccount = (EditText) findViewById(R.id.login_et_account);
        userPassWord = (EditText) findViewById(R.id.login_et_password);
        qq_login = (ImageView) findViewById(R.id.iv_qqLogin);
        wx_login = (ImageView) findViewById(R.id.iv_wechatLogin);
        wb_login = (ImageView) findViewById(R.id.iv_weiboLogin);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_register:
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_login:
                checkAccountAndPassword();
                break;
            case R.id.iv_qqLogin:
                qqLogin();
                break;
            case R.id.iv_wechatLogin:
                break;
            case R.id.iv_weiboLogin:
                break;
        }
    }

    /**
     * QQ登陆
     */
    private void qqLogin() {
        // 先在对应的平台上授权 例如：QQ
        // 先获取平台对象
        Platform qq = ShareSDK.getPlatform(LoginActivity.this, QQ.NAME);
        // 代表使用的授权方式是sso 使用手机客户端进行授权
        qq.SSOSetting(true);
        //设置授权监听
        qq.setPlatformActionListener(new PlatformActionListener() {
            /**
             * 授权成功
             * @param platform
             * @param i
             * @param hashMap
             */
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                PlatformDb platformDb = platform.getDb();
                //用户姓名
                Log.e("platform.getName()",platform.getName());
                qqAccount = platformDb.getUserName();
                qqPassword = "123456";
                //用户头像
                iconUrl = platformDb.getUserIcon();
                //用户在此平台的唯一标识
                MyApplication.mUser.setId(platformDb.getUserId());
                MyApplication.mUser.setLogin(false);
                MyApplication.mAccount.setAccount("qq_"+qqAccount);
                MyApplication.mAccount.setPassword(qqPassword);
                SharepreferencesUtilSystemSettings.putValue(LoginActivity.this,Constant.ID,MyApplication.mUser.getId());
                SharepreferencesUtilSystemSettings.putValue(LoginActivity.this,Constant.ISLOGIN,MyApplication.mUser.getIsLogin());
                SharepreferencesUtilSystemSettings.putValue(LoginActivity.this,Constant.USERACCOUNTCOOKIE,MyApplication.mAccount.getAccount());
                SharepreferencesUtilSystemSettings.putValue(LoginActivity.this,Constant.USERPASSWORDCOOKIE,MyApplication.mAccount.getPassword());
                handler.sendEmptyMessage(1);
            }

            /**
             * 授权不成功
             * @param platform
             * @param i
             * @param throwable
             */
            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                throwable.printStackTrace();
            }

            /**
             * 取消授权
             * @param platform
             * @param i
             */
            @Override
            public void onCancel(Platform platform, int i) {

            }
        });
        if (qq.isValid()){
            qq.removeAccount();
        }
        // 授权方式： 要数据不要功能
        qq.showUser(null);// 授权登录 在回调函数里获取用户信息
    }

    private void checkAccountAndPassword() {
        String account = userAccount.getText().toString();
        String password = userPassWord.getText().toString();
        if (account.equals("")||password.equals("")){
            Toast.makeText(LoginActivity.this,"请输入用户名或密码",Toast.LENGTH_LONG).show();
        }else {
            dialog.show();
            myBmobUtils.context = this;
            myBmobUtils.queryAccount(account,password);
        }

    }
}
